# -*- coding: UTF-8 -*-
import tkinter as tk
from PIL import ImageGrab
from Code.Utils.sc_func import Common
from Code.View.Datamation.sc_provide import view_gate
from Code.View.sc_module import WidgetTip

language_data = view_gate.query_language_data


class ScreenShot(object):
    """ 截屏实现类 """
    def __init__(self):
        self.sel = None
        self.last = None
        self.temp_png = '__temp__.png'
        self.img_key = '_SCREENSHOT_TEMP_'
        self.X = tk.IntVar(value=0)     # 用来记录鼠标左键按下的位置
        self.Y = tk.IntVar(value=0)
        self.top = tk.Toplevel()
        self.top.overrideredirect(True)
        width = self.top.winfo_screenwidth()
        height = self.top.winfo_screenheight()
        im = ImageGrab.grab()
        im.save(self.temp_png)
        im.close()
        view_gate.add_image_data.set_data((self.img_key, self.temp_png))
        self.canvas = tk.Canvas(self.top, width=width, height=height)
        self.canvas.create_image(width//2, height//2, image=view_gate.query_photo_image_data(self.img_key))
        self.canvas.bind('<Button-1>', self.on_left_button_down)
        self.canvas.bind('<B1-Motion>', self.on_left_button_move)
        self.canvas.bind('<ButtonRelease-1>', self.on_left_button_up)
        self.canvas.pack(fill='both', expand=1)

    def delete_last_draw(self):
        """ 删除刚画完的图形，要不然鼠标移动的时候是黑乎乎的一片矩形 """
        try:
            self.canvas.delete(self.last)
        except:
            pass

    def on_left_button_down(self, event):
        """ 鼠标左键按下的位置 """
        self.X.set(event.x)
        self.Y.set(event.y)
        self.sel = True

    def on_left_button_move(self, event):
        """ 鼠标左键移动，显示选取的区域 """
        if not self.sel:
            return
        self.delete_last_draw()
        self.last = self.canvas.create_rectangle(self.X.get(), self.Y.get(), event.x, event.y, width=2, outline='Red')

    def on_left_button_up(self, event):
        """ 获取鼠标左键抬起的位置，保存区域截图 """
        self.sel = False
        self.delete_last_draw()
        Common.sleep(0.1)
        left, right = sorted([self.X.get(), event.x])
        top, bottom = sorted([self.Y.get(), event.y])
        pic = ImageGrab.grab((left+1, top+1, right-1, bottom-1))
        save_name = "ScreenShot-{0}.png".format(Common.get_time(False))
        pic.save(save_name)
        self.top.destroy()
        Common.remove(self.temp_png)
        view_gate.del_image_data.set_data((self.img_key, ), asynccall=True)
        WidgetTip.info("{}: {}".format(language_data('SUCCESS'), save_name))

